package com.company.huisuo.biz.activity

import android.animation.ValueAnimator
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.company.huisuo.R
import com.company.huisuo.base.BaseActivity
import com.company.huisuo.biz.bean.PrizeConfig
import com.company.huisuo.biz.dialog.GameGroupRewardDialog
import com.company.huisuo.biz.dialog.IntimateSpacePrizeDialog
import com.company.huisuo.biz.dialog.SelectScriptDialog
import com.company.huisuo.databinding.ActivityIntimateSpaceBinding
import com.company.huisuo.ext.dp2px
import com.company.huisuo.ext.loadImg
import com.company.huisuo.ext.sp2px
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import kotlin.random.Random

/**
 * 亲密空间
 */
class IntimateSpaceActivity : BaseActivity<ActivityIntimateSpaceBinding>() {

    companion object {
        fun start(activity: Activity) {
            activity.startActivity(Intent(activity, IntimateSpaceActivity::class.java))
        }
    }

    private var isAnimating = false

    // 保存每个头像的初始角度（使用 View 对象作为 key）
    private val initialAngles = mutableMapOf<View, Float>()

    private val mIntimateSpacePrizeDialog by lazy {
        XPopup.Builder(this).asCustom(IntimateSpacePrizeDialog(this))
    }
    private val mRewardDialog by lazy {
        XPopup.Builder(this).asCustom(GameGroupRewardDialog(this) {

        })
    }

    private val mDanceView = arrayListOf<View>()

    override fun initView() {
        initDanceData()
        mBinding.ivBack.setOnClickListener {
            finish()
        }
        mBinding.llGroup1.setOnClickListener {
            chooseGroup(1)
        }
        mBinding.llGroup2.setOnClickListener {
            chooseGroup(2)
        }
        mBinding.llGroup3.setOnClickListener {
            chooseGroup(3)
        }
        mBinding.llGroup4.setOnClickListener {
            chooseGroup(4)
        }
        mBinding.ivStartGame.setOnClickListener {
            if (!isAnimating) {
                startRotationAnimation()
            }
        }
        mBinding.ivSearch.setOnClickListener {
            //选择剧本  intimate_space 亲密空间
            XPopup.Builder(this).asCustom(SelectScriptDialog(this,"intimate_space").apply {
                onConfirmListener = { gamePlanBean ->
                    println("选中的剧本: ${gamePlanBean.planName}")

//                    // 解析prizeConfig字段
//                    try {
//                        val prizeConfig = Gson().fromJson(gamePlanBean.prizeConfig, PrizeConfig::class.java)
//                        println("解析后的奖品配置: $prizeConfig")
//
//                        // 在添加新数据前先清空原有数据
//                        clearDanceData()
//
//                        // 使用解析后的数据创建舞蹈视图
//                        prizeConfig.gameItems?.forEach { prizeItem ->
//                            // 这里可以根据prizeItem的数据来创建舞蹈视图
//                            // 暂时使用默认的图标和参数，后续可以根据prizeItem的属性进行调整
//                            createDanceView(
//                                avatar = prizeItem.itemIcon?:"", // 默认图标，可以根据itemIcon调整 R.drawable.ic_intimate_avatar_1
//                                nameStr = prizeItem.itemName ?: "未知项目",
//                                angle = Random.nextInt(360), // 随机角度
//                                radius = 80 + Random.nextInt(200) // 随机半径
//                            )
//                        }
//                    } catch (e: Exception) {
//                        println("解析prizeConfig失败: ${e.message}")
//                        // 如果解析失败，使用默认数据
//                        initDanceData()
//                    }
                }
            }).show()
        }
        mBinding.ivAdd.setOnClickListener {
            GameGroupActivity.start(this)
        }
    }

    override fun initData() {
        chooseGroup(2)

        // 保存每个动态创建的头像的初始角度
        mDanceView.forEach { view ->
            initialAngles[view] = getCircleAngle(view)
        }
    }

    private fun initDanceData() {



        //右上
        createDanceView(R.drawable.ic_intimate_avatar_1, "黎明觉醒", 10, 80)
        createDanceView(R.drawable.ic_intimate_avatar_2, "舌尖传花", 25, 180)
        createDanceView(R.drawable.ic_intimate_avatar_3, "当红少爷", 40, 300)
        createDanceView(R.drawable.ic_intimate_avatar_4, "坦诚相待", 60, 300)
        createDanceView(R.drawable.ic_intimate_avatar_5, "眉目传情", 70, 450)
        createDanceView(R.drawable.ic_intimate_avatar_6, "耐力无限", 85, 250)
        //右下
        createDanceView(R.drawable.ic_intimate_avatar_5, "眉目传情", 100, 80)
        createDanceView(R.drawable.ic_intimate_avatar_2, "舌尖传花", 115, 180)
        createDanceView(R.drawable.ic_intimate_avatar_3, "当红少爷", 120, 300)
        createDanceView(R.drawable.ic_intimate_avatar_5, "眉目传情", 160, 450)
        createDanceView(R.drawable.ic_intimate_avatar_6, "耐力无限", 175, 180)
        //左下
        createDanceView(R.drawable.ic_intimate_avatar_5, "眉目传情", 190, 80)
        createDanceView(R.drawable.ic_intimate_avatar_2, "舌尖传花", 205, 180)
        createDanceView(R.drawable.ic_intimate_avatar_3, "当红少爷", 255, 375)
        createDanceView(R.drawable.ic_intimate_avatar_4, "坦诚相待", 240, 280)
        createDanceView(R.drawable.ic_intimate_avatar_5, "眉目传情", 250, 450)
        createDanceView(R.drawable.ic_intimate_avatar_6, "耐力无限", 265, 250)
        //左上
        createDanceView(R.drawable.ic_intimate_avatar_1, "黎明觉醒", 275, 80)
        createDanceView(R.drawable.ic_intimate_avatar_2, "舌尖传花", 285, 180)
        createDanceView(R.drawable.ic_intimate_avatar_3, "当红少爷", 305, 375)
        createDanceView(R.drawable.ic_intimate_avatar_4, "坦诚相待", 300, 300)
        createDanceView(R.drawable.ic_intimate_avatar_6, "耐力无限", 325, 250)
    }

    /**
     * 清空舞蹈数据
     */
    private fun clearDanceData() {
        // 从父布局中移除所有动态创建的视图
        mDanceView.forEach { view ->
            mBinding.clLayout.removeView(view)
        }
        
        // 清空视图集合
        mDanceView.clear()
        
        // 清空初始角度映射
        initialAngles.clear()
        
        println("已清空所有舞蹈数据")
    }

    private fun createDanceView(
        avatar: Int, nameStr: String, angle: Int, radius: Int
    ): LinearLayout {
        val image = ImageView(this)
        val imageParam = LinearLayout.LayoutParams(50.dp2px(), 50.dp2px())
        image.layoutParams = imageParam
        
        // 设置圆形图片
        image.apply {
            // 设置背景为圆形
            background = resources.getDrawable(R.drawable.circle_background, null)
            // 设置裁剪为圆形
            clipToOutline = true
            // 设置图片缩放类型为居中裁剪
            scaleType = ImageView.ScaleType.CENTER_CROP
            // 设置内边距，确保图片在圆形内显示
            setPadding(2.dp2px(), 2.dp2px(), 2.dp2px(), 2.dp2px())
        }
        
//        image.loadImg(avatar)
        image.setImageResource(avatar)

        val name = TextView(this)
        val nameParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT
        ).apply {
            topMargin = 4.dp2px()
        }
        name.layoutParams = nameParam
        name.text = nameStr
        name.setTextColor(Color.parseColor("#9AEBDB"))
        name.textSize = 7f

        val layout = LinearLayout(this)
        layout.orientation = LinearLayout.VERTICAL  // 设置垂直方向
        layout.gravity = Gravity.CENTER
        val layoutParam = ConstraintLayout.LayoutParams(
            ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT
        ).apply {
            circleConstraint = R.id.centerView
            circleRadius = radius.dp2px()
            circleAngle = angle.toFloat()
        }
        layout.layoutParams = layoutParam
        layout.addView(image)
        layout.addView(name)
        layout.translationZ = -1f
        mDanceView.add(layout)
        mBinding.clLayout.addView(layout)
        return layout
    }

    private fun chooseGroup(group: Int) {
        mBinding.apply {
            group1Left.isSelected = group == 1
            group1Right.isSelected = group == 1

            group2Left.isSelected = group == 2
            group2Right.isSelected = group == 2

            group3Left.isSelected = group == 3
            group3Right.isSelected = group == 3

            group4Left.isSelected = group == 4
            group4Right.isSelected = group == 4
        }
    }

    /**
     * 获取view的CircleAngle
     */
    private fun getCircleAngle(view: View): Float {
        val layoutParams = view.layoutParams as? ConstraintLayout.LayoutParams
        return layoutParams?.circleAngle ?: 0f
    }

    /**
     * 设置view的CircleAngle
     */
    private fun setCircleAngle(view: View, angle: Float) {
        val layoutParams = view.layoutParams as? ConstraintLayout.LayoutParams
        layoutParams?.circleAngle = angle % 360
        view.layoutParams = layoutParams
    }

    /**
     * 开始旋转动画
     */
    private fun startRotationAnimation() {
        isAnimating = true

        // 生成随机角度（720-1080度，即2-3圈，使用浮点数实现纯随机）
        val randomAngle = 720f + Random.nextFloat() * 360f

        // 创建动画
        val animator = ValueAnimator.ofFloat(0f, randomAngle).apply {
            duration = 2000 // 2秒
            interpolator = DecelerateInterpolator() // 减速插值器，模拟减速停止效果
        }

        animator.addUpdateListener { animation ->
            val currentAngle = animation.animatedValue as Float

            // 更新所有动态创建的头像的角度
            mDanceView.forEach { view ->
                val initialAngle = initialAngles[view] ?: 0f
                setCircleAngle(view, initialAngle + currentAngle)
            }
        }

        animator.addListener(object : android.animation.AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: android.animation.Animator) {
                // 动画结束后，更新初始角度为当前角度
                mDanceView.forEach { view ->
                    initialAngles[view] = getCircleAngle(view)
                }
                isAnimating = false

                // 动画完全结束后的回调
                onAnimationComplete()
            }
        })

        animator.start()
    }

    /**
     * 动画完全结束后的回调函数
     */
    private fun onAnimationComplete() {
        val random = Random.nextInt()
        if (random % 2 == 0) {
            mIntimateSpacePrizeDialog.show()
        } else {
            mRewardDialog.show()
        }
    }
}